package com.supor.aiot.common.app;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.ViewGroup;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSONObject;
import com.alipay.mobile.framework.quinoxless.QuinoxlessFramework;
import com.alipay.mobile.h5container.api.H5Page;
import com.alipay.mobile.h5container.api.H5Plugin;
import com.alipay.mobile.h5container.service.H5Service;
import com.alipay.mobile.nebula.provider.H5ViewProvider;
import com.alipay.mobile.nebula.provider.TinyOptionMenuViewProvider;
import com.alipay.mobile.nebula.util.H5Utils;
import com.alipay.mobile.nebula.view.H5NavMenuView;
import com.alipay.mobile.nebula.view.H5PullHeaderView;
import com.alipay.mobile.nebula.view.H5TitleView;
import com.alipay.mobile.nebula.view.H5WebContentView;
import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.config.HttpConstant;
import com.android.baseconfig.common.helper.ActivityManager;
import com.android.baseconfig.common.helper.PermissionsChecker;
import com.android.baseconfig.common.rxpermissions2.RxPermissions;
import com.android.baseconfig.common.utils.GetAndroidUniqueMark;
import com.android.baseconfig.common.utils.GsonUtil;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ThreadUtils;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.views.AppBasicDialog;
import com.google.gson.reflect.TypeToken;
import com.mpaas.framework.adapter.api.MPFramework;
import com.mpaas.mas.adapter.api.MPLogger;
import com.mpaas.nebula.adapter.api.MPNebula;
import com.mpaas.nebula.adapter.api.MpaasNebulaUpdateCallback;
import com.supor.aiot.common.R;
import com.supor.aiot.common.app.api.DeviceImpl;
import com.supor.aiot.common.app.api.UserImpl;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.entity.DeviceInfo;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.common.entity.RecordBean;
import com.supor.aiot.common.entity.UserInfo;
import com.supor.aiot.common.helper.ActivityHelper;
import com.supor.aiot.common.helper.CmccHelper;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.helper.ShareHelper;
import com.supor.aiot.common.helper.WsHelper;
import com.supor.aiot.common.interfaces.ISuporPresenter;
import com.supor.aiot.common.push.PushMsgService;
import com.supor.aiot.common.ui.activity.NFCDeviceActivity;
import com.supor.aiot.common.ui.activity.NfcWebActivity;
import com.supor.aiot.common.ui.activity.SuporPermissionActivity;
import com.supor.aiot.common.ui.activity.WebActivity;
import com.supor.aiot.common.ui.view.SuporJSApiPlugin;
import com.supor.aiot.common.ui.view.TinyNavigationBar;
import com.supor.aiot.common.ui.view.TinyOptionMenuView;
import com.supor.aiot.common.utils.CalendarReminderUtils;
import com.supor.aiot.common.utils.ExternalPathUtils;
import com.supor.aiot.common.utils.MarketUtils;
import com.supor.aiot.common.utils.NFCCheckUtils;
import com.supor.aiot.common.utils.NotNullUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

import androidx.fragment.app.FragmentActivity;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: native与H5交互 <br>
 * 作者: lei <br>
 * 日期: 2020/9/3 <br>
 */
public class SuporPresenter implements ISuporPresenter {
    public static long MSG_ID = 0;
    private static SuporPresenter instance = null;
    private Context context;
    private H5Service h5Service;
    private ShareHelper shareHelper;
    private CmccHelper cmccHelper;
    private TinyNavigationBar tinyNavigationBar;

    public static SuporPresenter getInstance() {
        if (instance == null) {
            instance = new SuporPresenter();
        }
        return instance;
    }

    private SuporPresenter() {
        initCustomService();
    }

    private void initCustomService() {
        if (!QuinoxlessFramework.initSuccess()) {
            ThreadUtils.execute(this::initCustomService, 50);
            return;
        }
        initCustomApi();
        initCustomTitle();
        h5Service = MPFramework.getExternalService(H5Service.class.getName());
    }

    public void init(Context context) {
        this.context = context;
        shareHelper = new ShareHelper(context);
    }

    public static boolean initSuccess() {
        return instance != null;
    }

    /**
     * 一键登录初始化，在主界面初始化，Application初始化有问题
     *
     * @param context
     */
    public void initCmcc(Context context) {
        cmccHelper = new CmccHelper(context);
    }

    /**
     * 自定义JSAPI
     */
    private void initCustomApi() {
        /*
         * 第一个参数，自定义 API 类的全路径
         * 第二个参数，BundleName，aar/inside可以直接填 ""
         * 第三个参数，作用于，可以直接填 "page"
         * 第四个参数，作用的 API，将你自定义的 API 以 String[] 的形式传入
         */
        MPNebula.registerH5Plugin(
                SuporJSApiPlugin.class.getName(),
                "",
                "page",
                new String[]{
                        H5Plugin.CommonEvents.EXIT_SESSION,
                        H5Plugin.CommonEvents.H5_PAGE_PHYSICAL_BACK,
                        H5Plugin.CommonEvents.H5_AL_JSAPI_RESULT_ERROR,
                        Constants.Fun.sendOnline,
                        Constants.Fun.sendCmd,
                        Constants.Fun.sendShareMsg,
                        Constants.Fun.sendShowNavigationBar,
                        Constants.Fun.sendUserInfo,
                        Constants.Fun.sendCmccAuthLogin,
                        Constants.Fun.sendGetAppInfo,
                        Constants.Fun.sendSetAppInfo,
                        Constants.Fun.sendSwitchServer,
                        Constants.Fun.sendSaveInfo,
                        Constants.Fun.sendJumpMemberCenter,
                        Constants.Fun.sendConfigNetwork,
                        Constants.Fun.sendUrlDisplay,
                        Constants.Fun.sendNFCBlender,
                        Constants.Fun.sendRequestPermission,
                        Constants.Fun.sendFeedback,
                        Constants.Fun.sendSaveUpgradeInfo,
                        Constants.Fun.sendGetUpgradeInfo,
                        Constants.Fun.sendStartPage,
                        Constants.Fun.sendStateChange,
                        Constants.Fun.sendTikRecipeStateChange,
                        Constants.Fun.sendTikRecipePageStart,
                        Constants.Fun.removeFromCalendar,
                        Constants.Fun.showToast,
                        Constants.Fun.addToCalendar
                });
    }

    private void initCustomTitle() {
        // 自定义标题栏
        MPNebula.setCustomViewProvider(new H5ViewProvider() {
            @Override
            public H5TitleView createTitleView(Context context) {
                // 返回自定义 title
                return (tinyNavigationBar = new TinyNavigationBar(context));
            }

            @Override
            public H5NavMenuView createNavMenu() {
                return null;
            }

            @Override
            public H5PullHeaderView createPullHeaderView(Context context, ViewGroup viewGroup) {
                return null;
            }

            @Override
            public H5WebContentView createWebContentView(Context context) {
                return null;
            }
        });
        // 自定义小程序右上角配置栏
        H5Utils.setProvider(TinyOptionMenuViewProvider.class.getName(),
                (TinyOptionMenuViewProvider) TinyOptionMenuView::new);
    }

    @Override
    public void reportShareStatus(int result) {
        JSONObject jo = new JSONObject();
        jo.put(Constants.Key.param_result, result);
        jo.put(Constants.Key.param_msgId, MSG_ID);
        jo.put(Constants.Key.param_time, SystemClock.uptimeMillis());
        sendDataToH5(jo, Constants.Fun.reportShareStatus);
    }

    @Override
    public void reportCmccLoginStatus(int result, String userInfo) {
        JSONObject jo = new JSONObject();
        jo.put(Constants.Key.param_result, result);
        jo.put(Constants.Key.param_userInfo, userInfo);
        jo.put(Constants.Key.param_time, SystemClock.uptimeMillis());
        // Logc.i("report CmccLoginStatus: " + jo.toJSONString());
        sendDataToH5(jo, Constants.Fun.reportCmccLoginStatus);
    }

    /**
     * 跳转验证码登录
     *
     * @param context
     * @param isFull
     */
    public void otherLogin(Context context, boolean isFull) {
        if (isFull) {
            ARouter.getInstance().build(PathUrl.PATH_LOGIN)
                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                            com.android.baseconfig.R.anim.activity_open_exit)
                    .navigation(context);
        } else {
            ARouter.getInstance().build(PathUrl.PATH_DIALOG_LOGIN)
                    .withTransition(0, 0)
                    .navigation(context);
        }
    }

    @Override
    public void reportConfigNetworkStatus(String result) {
        JSONObject jo = new JSONObject();
        jo.put(Constants.Key.param_result, result);
        Logc.i("report ConfigNetworkStatus: " + jo.toJSONString());
        sendDataToH5(jo, Constants.Fun.reportConfigNetworkStatus);
    }

    @Override
    public void reportNFCParams(String params) {
        Logc.i("report NFCParams: " + params);
        if (GlobalDataCache.recordBean != null) {
            // 处理C001设备
            if (GlobalDataCache.recordBean.getProductId().equalsIgnoreCase("C001")) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putInt(Constants.Key.param_type, 1);
                bundle.putString(Constants.Key.param_url, "https://www.supor.com" +
                        ".cn/M/disheslist?cid=2455");
                bundle.putString(Constants.Key.param_title, "涨厨艺");
                intent.putExtras(bundle);
                startActivity(intent, NfcWebActivity.class, true);
                GlobalDataCache.recordBean = null;
                GlobalDataCache.NFC_PARAMS = null;
                return;
            }
        }
        // JSONObject jo = new JSONObject();
        // jo.put(Constants.Key.param_params, params);
        // Logc.i("report NFCParams: " + jo.toJSONString());
        // sendDataToH5(jo, Constants.Fun.reportNFCParams);
        if (GlobalDataCache.recordBean == null) {
            return;
        }
        if (GlobalDataCache.deviceTree != null && GlobalDataCache.deviceTree.device != null) {
            // 确定NFC类型设备
            if (GlobalDataCache.recordBean.getWifiMac().length() == 0) {
                // Pid是否已接入Saas后台
                if (!NFCCheckUtils.checkPidAccess(GlobalDataCache.recordBean.getProductId())) {
                    Activity current = AppAgent.getCurrentActivity();
                    NFCCheckUtils.startResultActivity(current, NFCCheckUtils.STATUS_NO_EXIT, false);
                } else {
                    // 检查Pid是否已经添加
                    int count = 0;
                    for (DeviceInfo info : GlobalDataCache.deviceTree.device) {
                        if (GlobalDataCache.recordBean.getProductId().equalsIgnoreCase(info.pid)) {
                            count++;
                        }
                        if (count > 1) {
                            break;
                        }
                    }
                    if (count == 0) {
                        // 跳转绑定页面
                        ARouter.getInstance()
                                .build(PathUrl.PATH_NFC_DEVICE_GUIDE)
                                .withString("productId", GlobalDataCache.recordBean.getProductId())
                                .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                        com.android.baseconfig.R.anim.activity_open_exit)
                                .navigation();
                    } else {
                        // 判断是否为NFC标签
                        if (GlobalDataCache.recordBean.getSn().length() == 0) {
                            // NFC标签只能绑定一个设备
                            // 跳转小程序
                            for (DeviceInfo info : GlobalDataCache.deviceTree.device) {
                                JSONObject jo = JSONObject.parseObject(GsonUtil.getInstance().toJson(info));
                                jo.put("deviceData", jo.getString("originalData"));
                                jo.remove("originalData");
                                if ((!TextUtils.isEmpty(GlobalDataCache.recordBean.getProductId())
                                        && GlobalDataCache.recordBean.getProductId().equalsIgnoreCase(info.pid))) {
                                    if (Constants.Type.TYPE_VOLTAGE_POT.equalsIgnoreCase(info.model)) {
                                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_VOLTAGE_POT,
                                                jo.toJSONString());
                                    } else if (Constants.Type.TYPE_VOLTAGE_POT_C100.equalsIgnoreCase(info.model)) {
                                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_VOLTAGE_POT_3L,
                                                jo.toJSONString());
                                    } else if (Constants.Type.TYPE_ELECTRIC_SAUCEPAN.equalsIgnoreCase(info.model)) {
                                        AppAgent.startDevicePage(Constants.App.TINY_ELECTRIC_SAUCEPAN,
                                                jo.toJSONString());
                                    } else if (Constants.Type.TYPE_BLENDER_66R.equalsIgnoreCase(info.model)) {
                                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_66R,
                                                jo.toJSONString());
                                    }  else if (Constants.Type.TYPE_BLENDER_65S.equalsIgnoreCase(info.model)) {
                                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_65S,
                                                jo.toJSONString());
                                    }  else if (Constants.Type.TYPE_BLENDER_905S.equalsIgnoreCase(info.model)) {
                                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_905S,
                                                jo.toJSONString());
                                    }  else if (Constants.Type.TYPE_BLENDER_906R.equalsIgnoreCase(info.model)) {
                                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_906R,
                                                jo.toJSONString());
                                    }
                                    break;
                                }
                            }
                        } else {
                            // NFC模块需要Pid + Uid一起判断
                            boolean isExit = false;
                            for (DeviceInfo info : GlobalDataCache.deviceTree.device) {
                                JSONObject jo = JSONObject.parseObject(GsonUtil.getInstance().toJson(info));
                                jo.put("deviceData", jo.getString("originalData"));
                                jo.remove("originalData");
                                if (info.mac.equalsIgnoreCase(GlobalDataCache.recordBean.getSn())) {
                                    if (Constants.Type.BLENDER_Q8.equalsIgnoreCase(info.model)) {
                                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER,
                                                jo.toJSONString());
                                    } else if (Constants.Type.TYPE_ELECTRIC_SAUCEPAN_C18.equalsIgnoreCase(info.model)) {
                                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_ELECTRIC_SAUCEPAN_C18,
                                                jo.toJSONString());
                                    }
                                    isExit = true;
                                    break;
                                } else {
                                    // 只针对已绑定的NFC模块类设备
                                    if (Constants.Type.TYPE_BLENDER_Q8.equalsIgnoreCase(info.pid)
                                            || Constants.Type.ELECTRIC_SAUCEPAN_C18.equalsIgnoreCase(info.pid)) {
                                        // 判断mac是否为虚拟的
                                        if (info.mac.length() == 15) {
                                            String newMac = GlobalDataCache.recordBean.getSn();
                                            // 更新mac，然后再跳转小程序
                                            DeviceImpl.getInstance().updateMac(newMac, info.mac, "Supor").subscribe(result -> {
                                                if (result.data) {
                                                    // 刷新设备列表
                                                    GlobalDataCache.getBindDevice();
                                                    // 跳转小程序
                                                    jo.put("did", newMac);
                                                    jo.put("mac", newMac);
                                                } else {
                                                    Logc.e("更新UID失败");
                                                }
                                                if (Constants.Type.BLENDER_Q8.equalsIgnoreCase(info.model)) {
                                                    AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER,
                                                            jo.toJSONString());
                                                } else if (Constants.Type.TYPE_ELECTRIC_SAUCEPAN_C18.equalsIgnoreCase(info.model)) {
                                                    AppAgent.startDevicePage(Constants.App.TINY_DEVICE_ELECTRIC_SAUCEPAN_C18,
                                                            jo.toJSONString());
                                                }
                                            }, throwable -> {
                                                Logc.e("updateMac: " + throwable);
                                            });
                                            isExit = true;
                                            break;
                                        }
                                    }
                                }
                            }
                            // Uid并未添加
                            if (!isExit) {
                                // 跳转绑定页面，重新绑定
                                ARouter.getInstance()
                                        .build(PathUrl.PATH_NFC_DEVICE_GUIDE)
                                        .withString("productId", GlobalDataCache.recordBean.getProductId())
                                        .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                                com.android.baseconfig.R.anim.activity_open_exit)
                                        .navigation();
                            }
                        }
                    }
                }
                GlobalDataCache.recordBean = null;
                GlobalDataCache.NFC_PARAMS = null;
                return;
            }
            // 有匹配的设备，跳转设备详情页
            for (DeviceInfo info : GlobalDataCache.deviceTree.device) {
                if (info.mac.equalsIgnoreCase(GlobalDataCache.recordBean.getWifiMac())
//                        && (!TextUtils.isEmpty(GlobalDataCache.recordBean.getProductId())
//                        && info.pid.equalsIgnoreCase(GlobalDataCache.recordBean.getProductId()))
                ) {
                    JSONObject jo = JSONObject.parseObject(GsonUtil.getInstance().toJson(info));
                    jo.put("deviceData", jo.getString("originalData"));
                    jo.remove("originalData");
                    if (Constants.Type.TYPE_CHEF_MACHINE.equalsIgnoreCase(info.type)) {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_C,
                                jo.toJSONString());
                    } else if (Constants.Type.TYPE_OVEN.equalsIgnoreCase(info.type)) {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_OVEN,
                                jo.toJSONString());
                    } else if (Constants.Type.TYPE_RICE_COOKER.equalsIgnoreCase(info.type)) {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_RICE_COOKER_85A,
                                jo.toJSONString());
                    }
                    GlobalDataCache.recordBean = null;
                    GlobalDataCache.NFC_PARAMS = null;
                    return;
                }
            }
        }

        // 默认跳转添加设备页面
        if (GlobalDataCache.recordBean.getWifiMac().length() == 0) {
            // 切换环境后碰一碰，重新获取产品列表
            if (GlobalDataCache.productTypeList == null) {
                DeviceImpl.getInstance().getAllProduct().subscribe(result -> {
                    List<ProductType> productTypeList = result.data.rows;
                    for (ProductType productType : productTypeList) {
                        if (productType.Children == null) {
                            continue;
                        }
                        for (ProductType.ProductModel child : productType.Children) {
                            if (TextUtils.isEmpty(child.modelPicture)) {
                                child.modelPicture = productType.modelPicture;
                            }
                            // pid
                            child.productId = child.salsModelName;
                        }
                    }
                    GlobalDataCache.productTypeList =
                            GsonUtil.getInstance().toObject(GsonUtil.getInstance().toJson(productTypeList), new TypeToken<List<ProductType>>() {
                            }.getType());

                    checkPid();
                }, throwable -> {
                    Logc.e("accept: " + throwable);
                });
            } else {
                checkPid();
            }
        } else {
            if (AppAgent.getCurrentActivity().getClass()
                    .getName().equals("com.supor.aiot.home.ui.device.AddDeviceActivity")) return;
            ARouter.getInstance()
                    .build(PathUrl.PATH_ADD_DEVICE)
                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                            com.android.baseconfig.R.anim.activity_open_exit)
                    .navigation();
            GlobalDataCache.recordBean = null;
            GlobalDataCache.NFC_PARAMS = null;
        }
    }

    private void checkPid() {
        // Pid是否已接入Saas后台
        if (!NFCCheckUtils.checkPidAccess(GlobalDataCache.recordBean.getProductId())) {
            Activity current = AppAgent.getCurrentActivity();
            NFCCheckUtils.startResultActivity(current, NFCCheckUtils.STATUS_NO_EXIT, false);
        } else {
            // NFC设备直接跳转NFC绑定页面
            ARouter.getInstance()
                    .build(PathUrl.PATH_NFC_DEVICE_GUIDE)
                    .withString("productId", GlobalDataCache.recordBean.getProductId())
                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                            com.android.baseconfig.R.anim.activity_open_exit)
                    .navigation();
        }
        GlobalDataCache.recordBean = null;
        GlobalDataCache.NFC_PARAMS = null;
    }

    @Override
    public void reportDownloadStatus(String params) {
        JSONObject jo = new JSONObject();
        jo.put(Constants.Key.param_params, params);
        sendDataToH5(jo, Constants.Fun.reportDownloadStatus);
    }

    @Override
    public void reportPermission(int result, int type) {
        JSONObject jo = new JSONObject();
        jo.put(Constants.Key.param_result, result);
        jo.put(Constants.Key.param_type, type);
        sendDataToH5(jo, Constants.Fun.reportPermission);
    }

    @Override
    public void reportCloseAccount(int result) {
        JSONObject jo = new JSONObject();
        jo.put(Constants.Key.param_result, result);
        Logc.i("report CloseAccount: " + jo.toJSONString());
        sendDataToH5(jo, Constants.Fun.reportCloseAccount);
    }

    @Override
    public void reportBindStatus(int status, String mac, String did) {
        JSONObject jo = new JSONObject();
        jo.put(Constants.Key.param_status, status);
        jo.put(Constants.Key.param_mac, mac);
        jo.put(Constants.Key.param_did, did);
        Logc.i("report BindStatus: " + jo.toJSONString());
        sendDataToH5(jo, Constants.Fun.reportBindStatus);
    }

    @Override
    public void reportOnline(String mac, String did, int online) {
        JSONObject jo = new JSONObject();
        jo.put(Constants.Key.param_online, online);
        jo.put(Constants.Key.param_mac, mac);
        jo.put(Constants.Key.param_did, did);
        Logc.i("reportOnline: " + jo.toJSONString());
        sendDataToH5(jo, Constants.Fun.reportOnline);
    }

    @Override
    public void reportCmd(String mac, String did, String value) {
        JSONObject jo = new JSONObject();
        jo.put(Constants.Key.param_value, value);
        jo.put(Constants.Key.param_mac, mac);
        jo.put(Constants.Key.param_did, did);
        // Logc.i("reportCmd: " + jo.toJSONString());
        sendDataToH5(jo, Constants.Fun.reportCmd);
    }

    @Override
    public void reportDeviceTree(String device) {
        JSONObject jo = new JSONObject();
        jo.put(Constants.Key.param_device, device);
        Logc.i("reportDeviceTree: " + jo.toJSONString());
        sendDataToH5(jo, Constants.Fun.reportDeviceTree);
    }

    @Override
    public void reportRecipeCommInfo(String recipeId, int commType) {
        JSONObject jo = new JSONObject();
        jo.put(Constants.Key.COOKING_ID, recipeId);
        jo.put(Constants.Key.COOKING_COMM_TYPE, commType);
        Logc.i("reportRecipeCommInfo: " + jo.toJSONString());
        sendDataToH5(jo, Constants.Fun.reportRecipeCommInfo);
    }

    public void reportSwitchTab(int tab) {
        JSONObject jo = new JSONObject();
        jo.put(Constants.Key.param_type, tab);
        Logc.i("report SwitchTab: " + jo.toJSONString());
        // sendDataToH5(jo, Constants.Fun.reportSwitchTab);
    }

    @Override
    public void reportNFCWriteStatus(int status) {
        JSONObject jo = new JSONObject();
        jo.put(Constants.Key.param_status, status);
        Logc.i("report NFCWriteStatus: " + jo.toJSONString());
        sendDataToH5(jo, Constants.Fun.reportNFCWriteStatus);
    }

    @Override
    public void reportNewMac(String newMac) {
        JSONObject jo = new JSONObject();
        jo.put(Constants.Key.param_mac, newMac);
        Logc.i("report newMac: " + jo.toJSONString());
        sendDataToH5(jo, Constants.Fun.reportNewMac);
    }

    /**
     * <p> wxInstalled  0表示微信未安装 ；1表示微信已安装；
     * <p> dyInstalled  0表示抖音未安装 ；1表示抖音已安装；
     * <p> wbInstalled  0表示微博未安装 ；1表示微博已安装；
     */
    @Override
    public void reportShareChannel() {
        JSONObject jo = new JSONObject();
        jo.put(Constants.Key.param_wxInstalled,
                (MarketUtils.getTools().isInstalled(AppAgent.getApp(), Constants.App.WeixinPackage) ? 1 : 0));
        jo.put(Constants.Key.param_dyInstalled,
                (MarketUtils.getTools().isInstalled(AppAgent.getApp(), Constants.App.DouyinPackage) ? 1 : 0));
        jo.put(Constants.Key.param_wbInstalled,
                (MarketUtils.getTools().isInstalled(AppAgent.getApp(), Constants.App.WeiboPackage) ? 1 : 0));
        Logc.i("report reportShareChannel: " + jo.toJSONString());
        sendDataToH5(jo, Constants.Fun.reportShareChannel);
    }

    @Override
    public void reportCupCondition(String cValue) {
        JSONObject jo = new JSONObject();
        jo.put(Constants.Key.param_status, cValue);
        Logc.i("report reportCupCondition: " + jo.toJSONString());
        sendDataToH5(jo, Constants.Fun.reportCupCondition);
    }

    /**
     * native向H5发送数据
     *
     * @param jo  data
     * @param fun 方法
     */
    private void sendDataToH5(JSONObject jo, String fun) {
        final H5Page h5Page = h5Service.getTopH5Page();
        if (null != h5Page) {
            // native 向小程序发送事件的方法
            h5Page.getBridge().sendDataWarpToWeb(fun, jo, null);
        }
    }

    @Override
    public void sendOnline(String mac) {
    }

    @Override
    public void sendCmd(int cmd, String mac, String did, String value) {
        Logc.i("sendCmd: value: " + value);
        if (cmd == 1) {
            WsHelper.getInstance().c2sWrite(mac, did, value);
        } else if (cmd == 2) {
            WsHelper.getInstance().c2sRead(mac, did, value);
        }
    }

    @Override
    public void sendShareMsg(JSONObject jo) {
        // shareHelper.shareMsg(jo);
        ThreadUtils.execute(() -> shareHelper.shareMsg(jo));
    }

    @Override
    public void sendShowNavigationBar(int visibility) {
        tinyNavigationBar.showNavigationBar(visibility);
    }

    @Override
    public void sendUserInfo(JSONObject jo) {
    }

    @Override
    public void sendCmccAuthLogin(int state) {
        Logc.i("sendCmccAuthLogin: " + state);
        if (AppAgent.isSwitchBackground()) {
            Logc.v("runningBackground");
            return;
        }
        if (state == 1) {
            cmccHelper.displayLogin(true);
        } else {
            new Handler().postDelayed(() -> cmccHelper.quit(), 70);
        }
    }

    @Override
    public void sendGetAppInfo(JSONObject jo) {
        Logc.i("sendGetAppInfo jo: " + jo);
        String tinyVersion = jo.getString(Constants.Key.param_tinyVersion);
        if (!TextUtils.isEmpty(tinyVersion)) {
            BaseSharedPreferences.setString(AppAgent.getApp(),
                    Constants.Key.param_tinyVersion, tinyVersion);
        }
    }

    @Override
    public void sendSetAppInfo(JSONObject jo) {
        Logc.i("sendSetAppInfo jo: " + jo);
        String tinyVersion = jo.getString(Constants.Key.param_tinyVersion);
        if (!TextUtils.isEmpty(tinyVersion)) {
            BaseSharedPreferences.setString(AppAgent.getApp(),
                    Constants.Key.param_tinyVersion, tinyVersion);
        }
    }

    @Override
    public void sendSwitchServer(int server) {
    }

    @Override
    public void sendSaveInfo(JSONObject jo) {
    }

    /**
     * 用户登录退出后处理逻辑
     *
     * @param userInfo
     * @param isRefreshDevice 是否刷新设备列表
     */
    public void saveInfo(UserInfo userInfo, boolean isRefreshDevice) {
        ThreadUtils.execute(() -> {
            try {
                if (TextUtils.isEmpty(userInfo.getPasswd())) {
                    String token = BaseSharedPreferences.getString(AppAgent.getApp(), HttpConstant.TOKEN);
                    if (TextUtils.isEmpty(token)) {
                        return;
                    }
                    userInfo.setPasswd(token);
                }
                Logc.i("saveInfo jo: " + userInfo.toString());
                BaseSharedPreferences.setString(AppAgent.getApp(), Constants.Key.USER_INFO,
                        GsonUtil.getInstance().toJson(userInfo));
                GlobalDataCache.userInfo = GsonUtil.getInstance().toObject(BaseSharedPreferences.getString(AppAgent.getApp()
                        , Constants.Key.USER_INFO), UserInfo.class);
                String token = userInfo.getPasswd();
                if (!TextUtils.isEmpty(token)) {
                    BaseSharedPreferences.setString(AppAgent.getApp(), HttpConstant.TOKEN, token);
                }
                AppAgent.setLogin(true);
                if (isRefreshDevice) {
                    WsHelper.getInstance().init(AppAgent.getApp(), true);
                    GlobalDataCache.getBindDevice();
                }
                // 登录成功后上报一次用户信息到H5
                reportCmccLoginStatus(1, GsonUtil.getInstance().toJson(userInfo));
                String uniqueId = BaseSharedPreferences.getString(AppAgent.getApp(), Constants.Key.UNIQUE_ID);
                if (TextUtils.isEmpty(uniqueId)) {
                    uniqueId = GetAndroidUniqueMark.getUniqueId(AppAgent.getApp());
                    Logc.d("getUniqueId: " + uniqueId);
                    GlobalDataCache.uniqueId = uniqueId;
                    PushMsgService.bindUser();
                    PushMsgService.uploadThridToken();
                    BaseSharedPreferences.setString(AppAgent.getApp(), Constants.Key.UNIQUE_ID, uniqueId);
                }
                // Logc.e("sendSaveInfo userInfo: " + userInfo);

                pushAppToken();
                Logc.d("userInfo.userId: " + GlobalDataCache.userInfo.getBossUserId());
                PushMsgService.bindUser();
                PushMsgService.uploadThridToken();
                MPLogger.setUserId(GlobalDataCache.userInfo.getBossUserId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 用户和手机唯一标识绑定，用于推送
     */
    @SuppressLint("CheckResult")
    public static void pushAppToken() {
        pushAppToken(GlobalDataCache.getUniqueId());
    }

    @SuppressLint("CheckResult")
    public static void pushAppToken(String uniqueId) {
        UserImpl.getInstance().pushAppToken(uniqueId).subscribe(result -> {
            Logc.i("pushAppToken result: " + result.toString());
        }, throwable -> {
            Logc.e("pushAppToken error: " + throwable.getMessage());
        });
    }

    @Override
    public void sendConfigNetwork(JSONObject jo) {
        // Logc.d("sendConfigNetwork jo: " + jo);
        String token = BaseSharedPreferences.getString(AppAgent.getApp(),
                HttpConstant.TOKEN);
        if (TextUtils.isEmpty(token)) {
            Logc.e("sendConfigNetwork: no found token, retry get user!");
            // reportGetAppInfo();
        }
        int type = jo.getIntValue(Constants.Key.param_type);
        String deviceStr = jo.getString(Constants.Key.param_device_info);
        if (TextUtils.isEmpty(deviceStr)) {
            Logc.e("deviceStr cant null");
            return;
        }
        DeviceInfo deviceInfo = GsonUtil.getInstance().toObject(deviceStr, DeviceInfo.class);
        if (deviceInfo == null) {
            Logc.e("deviceInfo cant null");
            return;
        }
        ProductType.ProductModel productModel = null;
        if (GlobalDataCache.productTypeList != null) {
            for (ProductType productType : GlobalDataCache.productTypeList) {
                for (ProductType.ProductModel child : productType.Children) {
                    if (deviceInfo.model != null && deviceInfo.model.equalsIgnoreCase(child.modelId)) {
                        productModel = child;
                        break;
                    }
                }
                if (productModel != null) {
                    break;
                }
            }
        }
        if (productModel == null) {
            productModel = new ProductType.ProductModel();
            productModel.modelTypeId = deviceInfo.type;
            productModel.modelId = deviceInfo.model;
            productModel.modelName = deviceInfo.model;
            productModel.modelTypeName = deviceInfo.productName;
            productModel.modelPicture = deviceInfo.modelPicture;
        }
        String path = PathUrl.PATH_INPUT_WIFI;
        if (Constants.Type.BLENDER.equalsIgnoreCase(productModel.modelTypeId)) {
            // NFC设备直接跳转NFC绑定页面
            path = PathUrl.PATH_NFC_DEVICE_GUIDE;
        }
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constants.Key.PRODUCT_MODEL, productModel);
        ARouter.getInstance()
                .build(path)
                .with(bundle)
                .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                        com.android.baseconfig.R.anim.activity_open_exit)
                .navigation(AppAgent.getCurrentActivity());
    }

    @Override
    public void sendUrlDisplay(JSONObject jo) {
        Logc.d("sendUrlDisplay jo: " + jo);
        int type = jo.getIntValue(Constants.Key.param_type);
        String url = jo.getString(Constants.Key.param_url);
        String title = jo.getString(Constants.Key.param_title);
        if (TextUtils.isEmpty(url)) {
            ToastUtils.getInstance().showToast(AppAgent.getApp(), "url can't be null");
            return;
        }
        // 跳转商城
        if (type == 2) {
            ExternalPathUtils.jumpShoppe(AppAgent.getCurrentActivity(), url);
            return;
        }
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putInt(Constants.Key.param_type, type);
        bundle.putString(Constants.Key.param_url, url);
        if (!TextUtils.isEmpty(title)) {
            bundle.putString(Constants.Key.param_title, title);
        }
        intent.putExtras(bundle);
        startActivity(intent, WebActivity.class, true);
    }

    @Override
    public void sendRequestPermission(JSONObject jo) {
        Logc.i("sendRequestPermission jo: " + jo);
        ArrayList<String> list = new ArrayList<>();
        int type = jo.getIntValue(Constants.Key.param_type);
        if (type == 1) {
            list.add(Manifest.permission.CAMERA);
            list.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        } else if (type == 2) {
            list.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        } else if (type == 3) {
            list.add(Manifest.permission.READ_PHONE_STATE);
        } else if (type == 4) {
            list.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            list.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (list.size() == 0) {
            reportPermission(2, type);
            return;
        }
        String[] permissionStr = new String[list.size()];
        list.toArray(permissionStr);
        PermissionsChecker mPermissionsChecker = new PermissionsChecker(context);
        if (mPermissionsChecker.lacksPermissions(permissionStr)) {
            Intent intent = new Intent(AppAgent.getCurrentActivity(),
                    SuporPermissionActivity.class);
            intent.putStringArrayListExtra(Constants.Key.param_list, list);
            // param填2表示是小程序端请求权限
            intent.putExtra(Constants.Key.param_params, 2);
            intent.putExtra(Constants.Key.param_type, type);
            AppAgent.getCurrentActivity().startActivity(intent);
            AppAgent.getCurrentActivity().overridePendingTransition(R.anim.tranlate_in, 0);
        } else {
            reportPermission(1, type);
        }
    }

    @Override
    public void sendSaveUpgradeInfo(int state, String params) {
        Logc.d("sendSaveUpgradeInfo: state= " + state + ", params= " + params);
        if (state == 1) {
            BaseSharedPreferences.setString(context, Constants.Key.param_upgradeInfo, params);
        } else if (state == 2) {
            // TODO: 2021/7/8
            MarketUtils.getTools().startMarket(context, "com.supor.aiot");
        }
    }

    @Override
    public void sendGetUpgradeInfo() {
    }

    @Override
    public void sendFeedback() {
        String token = BaseSharedPreferences.getString(AppAgent.getApp(),
                HttpConstant.TOKEN);
        if (TextUtils.isEmpty(token)) {
            Logc.e("sendFeedback: no found token, retry get user!");
            // reportGetAppInfo();
        }
        Intent intent = new Intent();
        // startActivity(intent, FeedbackActivity.class, true);
        ARouter.getInstance().build(PathUrl.PATH_FEEDBACK).navigation();
    }

    @Override
    public void sendStartPage(JSONObject jo) {
        Logc.d("sendStartPage jo: " + jo);
        // 0 退出小程序|1 家庭页|2 菜篮子|3 烹饪记录列表|4 烹饪记录评价详情|5 烹饪记录评价填写|6 登录页
        int type = jo.getIntValue(Constants.Key.param_type);
        String params = jo.getString(Constants.Key.param_params);
        Bundle bundle = new Bundle();
        if (type == 0 || type == 8) {
            exitTiny();
        } else if (type == 1) {
            // exitTiny();
            ActivityManager.finishAll("MainActivity");
            RxBus3.getInstance().post(Constants.Tag.HOME_PAGE, 1);
        } else if (type == 2) {
            ActivityManager.finishAll("MainActivity");
            RxBus3.getInstance().post(Constants.Tag.HOME_PAGE, 3);
            // ARouter.getInstance().build(PathUrl.PATH_BASKET)
            //         .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
            //                 com.android.baseconfig.R.anim.activity_open_exit)
            //         .navigation(AppAgent.getCurrentActivity());
        } else if (type == 3) {
            String macArr = "";
            try {
                JSONObject paramObject = JSONObject.parseObject(params);
                macArr = paramObject.getString("mac");
            } catch (Exception e) {
                e.printStackTrace();
            }
            ARouter.getInstance()
                    .build(PathUrl.HomeMine.PATH_MINE_COOKING_RECORD)
                    .withString("RECORD_MAC_ADDR", macArr)
                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                            com.android.baseconfig.R.anim.activity_open_exit)
                    .navigation(AppAgent.getCurrentActivity());
        } else if (type == 4) {
            // @Autowired(name = "COOKING_EVAL_ID") //烹饪记录id
            // @Autowired(name = "COOKING_EVAL_NAME")//食谱名称
            // @Autowired(name = "COOKING_EVAL_IMG")//食谱封面
            String recordId = "";
            String recordName = "";
            String recordCover = "";
            try {
                JSONObject paramObject = JSONObject.parseObject(params);
                recordId = paramObject.getString("recordId");
                recordName = paramObject.getString("recordName");
                recordCover = paramObject.getString("recordCover");
            } catch (Exception e) {
                e.printStackTrace();
            }
            ARouter.getInstance()
                    .build(PathUrl.HomeMine.PATH_MINE_COOKING_EVAL_DETAIL)
                    .withString("COOKING_EVAL_ID", recordId)
                    .withString("COOKING_EVAL_NAME", recordName)
                    .withString("COOKING_EVAL_IMG", recordCover)
                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                            com.android.baseconfig.R.anim.activity_open_exit)
                    .navigation(AppAgent.getCurrentActivity());
        } else if (type == 5) {
            // @Autowired(name = "COOKING_EVAL_ID") //烹饪记录id
            // @Autowired(name = "COOKING_EVAL_NAME")//食谱名称
            // @Autowired(name = "COOKING_EVAL_IMG")//食谱封面
            String recordId = "";
            String recordName = "";
            String recordCover = "";
            try {
                JSONObject paramObject = JSONObject.parseObject(params);
                recordId = paramObject.getString("recordId");
                recordName = paramObject.getString("recordName");
                recordCover = paramObject.getString("recordCover");
            } catch (Exception e) {
                e.printStackTrace();
            }
            ARouter.getInstance()
                    .build(PathUrl.HomeMine.PATH_MINE_COOKING_EVAL)
                    .withString("COOKING_EVAL_ID", recordId)
                    .withString("COOKING_EVAL_NAME", recordName)
                    .withString("COOKING_EVAL_IMG", recordCover)
                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                            com.android.baseconfig.R.anim.activity_open_exit)
                    .navigation(AppAgent.getCurrentActivity());
        } else if (type == 6) {
            AppAgent.showLogin(true);
        } else if (type == 7) {
            String chefId = "";
            try {
                JSONObject paramObject = JSONObject.parseObject(params);
                chefId = paramObject.getString("chefId");
            } catch (Exception e) {
                e.printStackTrace();
            }
            ARouter.getInstance()
                    .build(PathUrl.PATH_COOKER_HOME)
                    .withString("CHEF_ID", chefId)
                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                            com.android.baseconfig.R.anim.activity_open_exit)
                    .navigation(AppAgent.getCurrentActivity());
        }
    }

    @Override
    public void sendStateChange(JSONObject jo) {
        Logc.d("sendStateChange jo: " + jo);
        // 1 设备更改名称; 2 解绑通知
        int type = jo.getIntValue(Constants.Key.param_type);
        String params = jo.getString(Constants.Key.param_params);
        if (type == 1) {
            try {
                JSONObject paramObject = JSONObject.parseObject(params);
                String did = paramObject.getString(Constants.Key.DID);
                String devAlias = paramObject.getString(Constants.Key.DEV_ALIAS);
                if (GlobalDataCache.deviceTree != null && GlobalDataCache.deviceTree.device != null) {
                    for (DeviceInfo info : GlobalDataCache.deviceTree.device) {
                        if (info.did.equalsIgnoreCase(did)) {
                            info.devAlias = devAlias;
                            RxBus3.getInstance().post(Constants.Tag.BINDING_STATUS,
                                    Constants.Value.SUCCESS);
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (type == 2) {
            try {
                JSONObject paramObject = JSONObject.parseObject(params);
                String mac = paramObject.getString(Constants.Key.MAC);
                if (GlobalDataCache.deviceTree != null && GlobalDataCache.deviceTree.device != null) {
                    for (DeviceInfo info : GlobalDataCache.deviceTree.device) {
                        if (info.mac.equalsIgnoreCase(mac)) {
                            GlobalDataCache.deviceTree.device.remove(info);
                            RxBus3.getInstance().post(Constants.Tag.BINDING_STATUS,
                                    Constants.Value.SUCCESS);
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void sendTikRecipeStateChange(JSONObject jo) {
        Logc.d("sendTikRecipeStateChange jo: " + jo);
        RxBus3.getInstance().post(Constants.TicPecipe.TIK_PECIPE_STATE,
                jo.toJSONString()
        );
    }

    @Override
    public void sendTikRecipePageStart(JSONObject jo) {
        int type = jo.getIntValue(Constants.Key.param_type);
        String params = jo.getString(Constants.Key.param_params);
        ARouter.getInstance().build(PathUrl.PATH_MD_VIDEO_LIST)
                .withInt("page_tyep", type)
                .withString("recipe_info", params)
                .withBoolean("start_from_repice_info", true)
                .navigation();
    }

    @Override
    public void sendNFCBlender(JSONObject jo) {
        Logc.d("sendNFCBlender jo: " + jo);
        String data = jo.getString(Constants.Key.DATA);
        String productId = jo.getString("productId");
        String grindingCup = jo.getString("grindingCup");
        String checkPermission = jo.getString("check_permission");
        if (!TextUtils.isEmpty(data)) {
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString(Constants.Key.DATA, data);
            bundle.putString(Constants.Key.PRODUCT_ID, productId);
            bundle.putString(Constants.Key.GRINDING_CUP, grindingCup);
            intent.putExtras(bundle);
            if (!TextUtils.isEmpty(checkPermission) && checkPermission.equals("1")) {
                new RxPermissions((FragmentActivity) AppAgent.getCurrentActivity()).request(
                        Manifest.permission.READ_CALENDAR,
                        Manifest.permission.WRITE_CALENDAR)
                        .subscribe(aBoolean -> {
                            if (aBoolean) {
                                startActivity(intent, NFCDeviceActivity.class, false);
                            } else {
                                Logc.i("permission request: failed");

                                AppBasicDialog.Builder builder = new AppBasicDialog.Builder(AppAgent.getCurrentActivity(), false);
                                builder.setTitle(R.string.permission_storage_title);
                                builder.setMessage(R.string.permission_storage_msg);
                                builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
                                builder.setPositiveButton(R.string.go_settings, (dialog, which) -> {
                                    ActivityHelper.startAppSettings(AppAgent.getCurrentActivity(), Constants.REQUEST_CODE2);
                                    dialog.dismiss();
                                });
                                AppBasicDialog commonDialog = builder.create();
                                commonDialog.setCancelable(false);
                                commonDialog.show();

                            }
                        });
            } else {
                startActivity(intent, NFCDeviceActivity.class, false);
            }

//            startActivity(intent, NFCDeviceActivity.class, false);
        }
    }

    @Override
    public void showToast(JSONObject jo) {
//        int type = jo.getIntValue(Constants.Key.param_type);
        String params = jo.getString(Constants.Key.param_params);
        JSONObject jsonObject = JSONObject.parseObject(params);
        ToastUtils.getInstance().showCustomToast(NotNullUtils.getNotNullValue(jsonObject.getString("title")));
    }

    @Override
    public long addToCalendar(JSONObject jo) {
        System.out.println("Constants.Fun.addToCalendar  addToCalendar thread " + Thread.currentThread().getName());
        return 0;
    }

    @Override
    public void removeFromCalendar(JSONObject jo) {
//        new RxPermissions((FragmentActivity) AppAgent.getCurrentActivity()).request(Manifest.permission.READ_CALENDAR,
//                Manifest.permission.WRITE_CALENDAR)
//                .subscribe(aBoolean -> {
//                    if (aBoolean) {
//                        CalendarReminderUtils.deleteCalendarEvent(AppAgent.getCurrentActivity(), );
////                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//
////                                CalendarReminderUtils.addCalendarEvent(getActivity(),
////                                        "事件标题",
////                                        "事件描述description",
////                                        format.parse("2022-01-19 17:00"),
////                                        0);
//
//                    } else {
//                        Logc.i("permission request: failed");
//                    }
//                });

    }


    /**
     * 退出小程序
     */
    public void exitTiny() {
        Activity activity = AppAgent.getCurrentActivity();
        Logc.d("activity: " + activity);
        if (activity != null && activity.getClass().getSimpleName().equalsIgnoreCase(
                "H5Activity")) {
            activity.onKeyDown(4, new KeyEvent(0, 4));
            activity.onBackPressed();
        }
    }

    /**
     * 启动应用
     *
     * @param activity
     */
    public void startMain(Activity activity) {
        Intent launchIntent = new Intent();
        launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        launchIntent.setComponent(new ComponentName("com.supor.aiot", "com.supor.aiot.MainActivity"));
        launchIntent.setAction(Intent.ACTION_MAIN);
        launchIntent.setFlags(FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(launchIntent);
    }

    private void startActivity(Intent intent, Class<?> clz, boolean ifAnim) {
        Activity current = AppAgent.getCurrentActivity();
        if (intent == null) {
            intent = new Intent();
        }
        intent.setClass(current, clz);
        current.startActivity(intent);
        if (ifAnim) {
            current.overridePendingTransition(R.anim.activity_open_enter,
                    R.anim.activity_open_exit);
        } else {
            current.overridePendingTransition(0, 0);
        }
    }

    private void startActivity(Class<?> clz, boolean ifAnim) {
        startActivity(null, clz, ifAnim);
    }

    public void startDisplay(Activity activity, RecordBean recordBean) {
        // 判断应用是否启动，若启动了则上传NFC参数信息，未启动则拉起应用，小程序启动后会主动获取NFC参数信息
        Activity bottomActivity = ActivityManager.getActivity(0);
        Activity current = AppAgent.getCurrentActivity();
        // Logc.i("bottom bottomActivity: " + (bottomActivity == null ? "null" : bottomActivity.getClass().getName()));

        if (bottomActivity != null && "MainActivity".equalsIgnoreCase(bottomActivity.getClass().getSimpleName())) {
            GlobalDataCache.ifNfcPop = false;
            if (recordBean.getProductId().equalsIgnoreCase("C001")) {
                // if (!(current != null && "MainActivity".equalsIgnoreCase(current.getClass().getSimpleName()))) {
                //     SuporPresenter.getInstance().reportNFCParams(GlobalDataCache.NFC_PARAMS);
                // }
                SuporPresenter.getInstance().reportNFCParams(GlobalDataCache.NFC_PARAMS);

            } else {
//                if (ConfigActivityManager.getActivityCount() == 0) {
//                    SuporPresenter.getInstance().reportNFCParams(GlobalDataCache.NFC_PARAMS);
//                }
                SuporPresenter.getInstance().reportNFCParams(GlobalDataCache.NFC_PARAMS);
            }
        } else {
            GlobalDataCache.ifNfcPop = true;
            startMain(activity);

            // PackageManager packageManager = activity.getPackageManager();
            // //                com.taobao.taobao   你想要启动的app的包名
            // Intent intent = packageManager.getLaunchIntentForPackage("com.supor.aiot");
            // //                不提示用户强制启动 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // activity.startActivity(intent);
            // activity.startActivity(new Intent(activity, MainActivity.class));
        }
        activity.finish();


        Logc.d("startDisplay recordBean: " + recordBean);
    }

    public void updateMac(String newMac, String oldMac) {
        DeviceImpl.getInstance().updateMac(newMac, oldMac, "Supor").subscribe(result -> {
            if (result.data) {
                // 刷新设备列表
                GlobalDataCache.getBindDevice();
                // 将新的UID发送给小程序
                SuporPresenter.getInstance().reportNewMac(newMac);
            } else {
                Logc.e("更新UID失败");
            }
        }, throwable -> {
            Logc.e("updateMac: " + throwable);
        });
    }

    /**
     * 更新小程序包，下载所需的小程序，不能全部更新，会把1.0的小程序也下下来
     */
    public void updateTiny() {
        Map<String, String> tinyMap = new HashMap<>();
        tinyMap.put(Constants.App.TINY_DEVICE_WATER_PURIFIER, "0.0.0");
        // tinyMap.put(Constants.App.TINY_DEVICE_C, "1.0.0");
        // tinyMap.put(Constants.App.TINY_GENERAL, "1.0.0");
        // tinyMap.put(Constants.App.TINY_DEVICE_OVEN, "1.0.0");
        // tinyMap.put(Constants.App.TINY_DEVICE_BLENDER, "1.0.0");
        ThreadUtils.execute(() -> MPNebula.updateApp(tinyMap, new MpaasNebulaUpdateCallback() {
            @Override
            public void onResult(final boolean success, final boolean isLimit) {
                // success 为是否成功
                Logc.d(success ? "offline package update success" : "offline package update failed");
            }
        }, true), 1000);
    }

    public CmccHelper getCmccHelper() {
        return cmccHelper;
    }

    /**
     * 显示一键登录
     *
     * @param isFull 是否全屏显示
     */
    public void displayLogin(boolean isFull) {
        if (cmccHelper != null) {
            cmccHelper.displayLogin(isFull);
        }
    }

    public ShareHelper getShareHelper() {
        return shareHelper;
    }


    public static void main(String[] args) {
    }

    public void onDestroy() {
        // UserImpl.getInstance().onDestroy();
        if (shareHelper != null) {
            shareHelper.destroy();
        }
    }
    //
    // public void downloadLaunchPage(LaunchPageHelper.LaunchPageCallback callback) {
    //     if (launchPageHelper != null) {
    //         launchPageHelper.downloadLaunchPage(callback);
    //     }
    // }
    //
    // public Bitmap getCacheLaunchPage() {
    //     if (launchPageHelper != null) {
    //         return launchPageHelper.getCacheLaunchPage();
    //     }
    //     return null;
    // }
    //
    // public Bitmap getCacheLaunchPage(String picId) {
    //     if (launchPageHelper != null) {
    //         return launchPageHelper.getCacheLaunchPage(picId);
    //     }
    //     return null;
    // }

}
